import { getCookieValue } from '~/utils';

export function buildWsUrl(url?: string | undefined | null, params: Record<string, string> = {}) {
  const hasDomain = /^wss?:\/\//.test(url ?? '');
  const origin = location.origin.replace(/^http/, 'ws');
  const prefixUrl = hasDomain ? url : origin + (url || '');
  const _url = new URL(`${prefixUrl}/ws/init`);
  const token = getCookieValue('token');

  if (token)
    _url.searchParams.append('token', token);

  Object.entries(params).forEach(([key, value]) => _url.searchParams.append(key, value));

  return _url.toString();
}
